package com.jt.aop;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.vo.SysResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Cx
 * @stage JT Of Fourth stage
 * @creat 2020-11-30 11:50
 */
@RestControllerAdvice   // AOP+异常通知
@Slf4j
public class SystemException {

    //当遇到某种类型的异常时才会执行
    @ExceptionHandler({RuntimeException.class})
    public Object exception(Exception e, HttpServletRequest request, HttpServletResponse response) {
        //log.info(e.getMessage());
        log.error(e.getMessage());
        e.printStackTrace();//输出异常信息
        // 获取callback请求参数
        String callback = request.getParameter("callback");
        // 判断是否为jsonp跨域请求
        if (StringUtils.hasLength(callback)) {
            JSONPObject jsonpObject = new JSONPObject(callback, SysResult.fail());
            return jsonpObject;
        }
        //如果出错,返回系统级别的报错数据即可
        return SysResult.fail();
    }

}
